﻿//《1》上传.csv格式的

//<input text="file" accept=".csv" />

//《2》上传.xls格式

//<input text="file"  accept="application/vnd.ms-excel"/>

//《3》上传.xslx格式

//<input text="fiel" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>

//《4》上传.png/.jpg/etc格式

//<input type="file" accept="text/plain" />

//《5》上传图片格式

//<input type="file" accept="image/*" />

//《6》上传.htm,.html格式

//<input type="file" accept="text/html" />

//《7》上传video(.avi, .mpg, .mpeg, .mp4)格式

//<input type="file" accept="video/*" />

//《8》上传audio(.mp3, .wav, etc)格式

//<input type="file" accept="audio/*" />

//《9》上传.pdf格式

//<input type="file" accept=".pdf" />

//《10》如果限制两种文件格式，同时限制

//<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel">
; (function ($) {
    var Attachment_Scroll = {};
    var methods = {
        module: 50,
        init: function (options) {
            var setting = {
                confirm: null,
                fileaccept: "",
                accept: "",
                beforeClick:null,
                typeID:null
            };
            var $this = $(this);
            if ($this.attr("accept") != undefined && $this.attr("accept") != "") {
                setting.accept = $this.attr("accept");
            }
            if ($this.attr("confirm") != undefined && $this.attr("confirm") != "") {
                var attachmentButton = null;
                eval("attachmentButton=" + $this.attr("confirm"));
                if ($.isFunction(attachmentButton)) {
                    setting.confirm = attachmentButton;
                }
            }
            if ($this.attr("beforeClick") != undefined && $this.attr("beforeClick") != "") {
                var attachmentbeforeClick = null;
                eval("attachmentbeforeClick=" + $this.attr("beforeClick"));
                if ($.isFunction(attachmentbeforeClick)) {
                    setting.beforeClick = attachmentbeforeClick;
                }
            }
            setting = $.extend(setting, options);

            //新增
            $this.click(function () {
                if (typeof (setting.beforeClick) == "function") {
                    setting.beforeClick($this, setting);
                }
                var _key = $(this).attr("attach-key");
                AJAX('/Content/Resources/html/wmpAttachmentForm.html', {}, function (d) {
                    var html = d;
                    var title = "附件上传";
                    var dialog = null;
                    layer.open({
                        type: 1,
                        anim: 'fadeIn',
                        title: '<span>' + title + '</span>',
                        content: html,
                        success: function (layero, index) {
                           // TransAll(layero);//加载完后翻译html

                            dialog = $(layero);
                            dialogResize(dialog, 960, 460, 0, true);

                            var index = dialog.attr("index");
                            var win_width = $(window).width();

                            //元素
                            var oFileInput = dialog.find(".fileInput");				//选择文件按钮
                            if (setting.accept != undefined && setting.accept != "") {
                                oFileInput.attr("accept", $this.attr("accept"));
                            }
                            var oFileList_parent = dialog.find(".fileList_parent");	//表格
                            var oFileBtn = dialog.find(".fileBtn");					//添加文件
                            var oUploadBtn = dialog.find(".uploadBtn");					//上传按钮

                            /*特殊处理，在iphone上打开摄像头会出现手机状态栏被消失导致的可视窗口高度发生变化导致的UI错位*/
                            var sHeight = $(window).height();
                            var oH = $("#layermbox" + index + " .layui-content").height();
                            var oHInt = setInterval(function () {
                                if (oHInt && $("#layermbox" + index + " .file-content").length == 0) {
                                    clearInterval(oHInt);
                                } else {
                                    var aHeight = $(window).height();
                                    if (aHeight != sHeight) {
                                        $("#layermbox" + index + " .layui-content").css("height", (oH + aHeight - sHeight) + "px");
                                    }
                                }
                            }, 1000);

                            var flieList = [];								//数据，为一个复合数组
                            var sizeObj = [];								//存放每个文件大小的数组，用来比较去重

                            dialog.on("change", "input.fileInput", function (event) {
                                analysisList(this.files);

                                dialog.find(".fileInput").replaceWith("<input type=\"file\" multiple=\"\" class=\"fileInput\">");
                            });
                            function fileType(name) {
                                var nameArr = name.split(".");
                                return nameArr[nameArr.length - 1].toLowerCase();
                            }
                            function bytesToSize(bytes) {
                                var sizes = ['Bytes', 'KB', 'MB'];
                                if (bytes == 0) return 'n/a';
                                var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
                                return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
                            }
                            //解析列表函数
                            function analysisList(obj) {
                                //如果没有文件
                                if (obj.length < 1) {

                                    return false;
                                }

                                for (var i = 0; i < obj.length; i++) {

                                    var fileObj = obj[i];		//单个文件
                                    var name = fileObj.name;	//文件名
                                    var size = fileObj.size;	//文件大小
                                    var type = fileType(name);	//文件类型，获取的是文件的后缀

                                    //if (name.toLowerCase().indexOf("mov") > -1) {
                                    //    //alert()
                                    //}

                                    //文件名称不能包含特殊字符
                                    if (/[{"'<>?/|%;)(#&+}]/.test(name)) {
                                        ShowError('“' + name + "” '" + window.LangMsg['msg_wmp_file_name_cannot_contain_char']);//文件名不能包含以下任何字符
                                        continue;
                                    }
                                    //文件大于30M，就不上传
                                    if (size > 30 * 1024 * 1024) {
                                        ShowError('“' + name + "” '" + window.LangMsg['msg_wmp_over_30m']); //超过了30M，不能上传
                                        continue;
                                    }

                                    //文件类型不为这三种，就不上传
                                    if (("exe/bat/msi").indexOf(type) > -1) {
                                        ShowError('“' + name + "” " + window.LangMsg['msg_wmp_file_type_wrong']);//文件类型不对，不能上传
                                        continue;
                                    }
                                    if (setting.fileaccept != undefined && setting.fileaccept != "") {
                                        //文件类型不为这三种，就不上传
                                        if (setting.fileaccept.indexOf(type) <= -1) {
                                            ShowError('文件类型不对，不能上传,只能上传【' + setting.fileaccept + '】格式文件');//文件类型不对，不能上传
                                            continue;
                                        }
                                    }

                                    //把文件大小放到一个数组中，然后再去比较，如果有比较上的，就认为重复了，不能上传
                                    if (sizeObj.indexOf(size) != -1) {
                                        ShowError('“' + name + "” " + window.LangMsg['msg_wmp_file_has_chosen']);//已经选择，不能重复上传
                                        continue;
                                    }

                                    //给json对象添加内容，得到选择的文件的数据
                                    var itemArr = [fileObj, name, size, type];	//文件，文件名，文件大小，文件类型
                                    flieList.push(itemArr);
                                    //把这个文件的大小放进数组中
                                    sizeObj.push(size);
                                }

                                createList()				//生成列表
                                oUploadBtn.show();			//上传按钮显示
                            };

                            //初始化文件列表为空样式
                            function fileUploadTip() {
                                var len = oFileList_parent.find("table").length;
                                if (len == 0) {
                                    oFileList_parent.html('<div class="file-empty-tip"><img src="/Content/img/upload.png" /><p class="red" data-langid="text_wmp_file_size_advise">建议单个附件不要超过10M，最大不能超过30M</p><p class="blue" data-langid="text_wmp_upload_file_safety_tips">安全提示：文件若上传，将被公司记录存档</p></div>');
                                   // TransAll(".file-empty-tip");//加载完后翻译html
                                }
                            }

                            //生成列表
                            function createList() {
                                if (flieList.length > 0) {
                                    $("#tbody_" + _key).find("tr.tbody_attachment_empty").remove();
                                }

                                //先清空元素内容
                                var str = '';
                                for (var i = 0; i < flieList.length; i++) {

                                    var fileData = flieList[i];		//flieList数组中的某一个
                                    var objData = fileData[0];		//文件
                                    var name = fileData[1];			//文件名
                                    var size = fileData[2];			//文件大小
                                    var type = fileData[3];			//文件类型
                                    var volume = bytesToSize(size);	//文件大小格式化
                                    if (name != null) {
                                        str += '<div class="table-responsive"><table class="table table-bordered"><tr><td class="td_title" data-langid="text_wmp_file_name">文件名称</td><td><span title="' + name + '">' + name + '</span></td></tr>';
                                        str += '<tr><td class="td_title" data-langid="text_wmp_file_type">文件类型</td><td>' + type + '</td></tr>';
                                        str += '<tr><td class="td_title" data-langid="text_wmp_file_size">文件大小</td><td>' + volume + '</td></tr>';
                                        str += '<tr><td class="td_title" data-langid="text_wmp_progress">进度</td><td>';
                                        str += '<div class="progressParent">';
                                        str += '<p class="progress"></p>';
                                        str += '<span class="progressNum">0%</span>';
                                        str += '</div>';
                                        str += '<a href="javascript:;" class="operation" data-langid="text_app_delete">删除</a>';
                                        str += '</td></tr></table></div>';
                                    }
                                }
                                oFileList_parent.html(str);

                                ///TransAll(oFileList_parent);//加载完后翻译html
                            }

                            //删除表格行
                            oFileList_parent.on("click", "a.operation", function () {
                                var oTable = $(this).parents("table");
                                var text = oTable.find("tr:first td:last").text()
                                var arrayIndex = 0;
                                oTable.remove();	//删除这一行
                                for (var key in flieList) {
                                    if (flieList[key][1] == text) {
                                        arrayIndex = key;
                                        break;
                                    }
                                }
                                flieList.splice(arrayIndex, 1);	//删除数据
                                sizeObj.splice(arrayIndex, 1);	//删除文件大小数组中的项
                                fileUploadTip();
                            });

                            //上传
                            oUploadBtn.on("click", function () {
                                var tr = oFileList_parent.find("table");		//获取所有tr列表
                                if (tr.length > 0) {
                                    oUploadBtn.off();
                                    oFileBtn.hide();

                                    var successNum = 0;					//已上传成功的数目
                                    oFileList_parent.off();					//取消删除事件
                                    oFileList_parent.find("a.operation").text(window.LangMsg['msg_wmp_acry']);
                                    for (var i = 0; i < tr.length; i++) {
                                        uploadFn(tr.eq(i), i);		//参数为当前项，下标
                                    }
                                } else {
                                    ShowError(window.LangMsg['msg_wmp_please_upload_file']);
                                }


                                function uploadFn(obj, i) {
                                    var formData = new FormData();
                                    var arrNow = flieList[i];						//获取数据数组的当前项
                                    // 从当前项中获取上传文件，放到 formData对象里面，formData参数以key name的方式
                                    var result = arrNow[0];							//数据

                                    if (arrNow.base64 != undefined && arrNow.base64 != "") {/*图片文件上传*/
                                        formData.append("file64", arrNow.base64);
                                    } else {/*非图片文件上传*/
                                        formData.append("imageFile", result);
                                    }

                                    var name = arrNow[1];							//文件名
                                    formData.append("filename", name);

                                    formData.append("ext", arrNow[3]);

                                

                                    var progress = obj.find(".progress");			//上传进度背景元素
                                    var progressNum = obj.find(".progressNum");		//上传进度元素文字
                                    var oOperation = obj.find("a.operation");		//按钮

                                    oOperation.text(window.LangMsg['msg_wmp_uploading']);							//改变操作按钮
                                    oOperation.off();
                                    var urlparam = "";
                                    var request = $.ajax({
                                        type: "POST",
                                        url: "/comm/upload" + urlparam,
                                        data: formData,			//这里上传的数据使用了formData 对象
                                        processData: false, 	//必须false才会自动加上正确的Content-Type
                                        contentType: false,
                                        dataType: "json",
                                        //上传成功后回调
                                        success: function (o, status, response) {
                                            var attachment = o;
                                            if (!attachment.success) {
                                                ShowError(attachment.msg);
                                            }
                                            successNum++;
                                            oOperation.text(window.LangMsg['msg_wmp_success']);
                                            if (typeof (setting.confirm) == "function") {
                                                setting.confirm(attachment.data);

                                            }
                                            if (successNum == tr.length) {
                                                ShowTip("所有附件已经上传完成！");
                                                layer.close(index);
                                            }

                                        },

                                        //上传失败后回调
                                        error: function () {
                                            ShowError(window.LangMsg['msg_app_upload_head_fail']);
                                            oOperation.text(window.LangMsg['msg_wmp_reupload']);
                                            oOperation.on("click", function () {
                                                request.abort();		//终止本次
                                                uploadFn(obj, i);
                                            });
                                        },
                                        beforeSend: function (xhr) {
                                            Loading();
                                        },
                                        complete: function (a, b, c) {
                                            Loading('close');
                                        }
                                    });


                                    //侦查附件上传情况 ,这个方法大概0.05-0.1秒执行一次
                                    function onprogress(evt) {
                                        var loaded = evt.loaded;	//已经上传大小情况
                                        var tot = evt.total;		//附件总大小
                                        var per = Math.floor(100 * loaded / tot);  //已经上传的百分比
                                        progressNum.html(per + "%");
                                        progress.css("width", per + "%");
                                    }

                                }
                            });
                        }
                    });
                }, "GET");
            });
        }

    };

    $.fn.AttachmentButton = function (method) {
        if (window != window.parent && typeof (window.parent.$("#").AttachmentButton) == "function") {
            if (arguments.length > 1) {
                return window.parent.$(this).AttachmentButton(method,arguments[1]);
            } else {
                return window.parent.$(this).AttachmentButton(method);
            }
        } else {
            if (methods[method]) {
                return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
            } else if (typeof method === 'object' || !method) {
                return methods.init.apply(this, arguments);
            } else {
                $.error('Method' + method + 'does not exist');
            }
        }
    };
})($);



